<template>
  <view class="revice_address_row">
    <view class="address_btn" v-if="!address.userName">
      <button @click="handleGetUserAddress" type="warn" plain>添加收获地址</button>
    </view>
    <view v-else class="user_info_row">
      <view class="user_info">
        <view> 收货人：{{address.userName}}</view>
        <view>{{address.all}}</view>
      </view>
      <view class="user_phone">{{address.telNumber}}</view>
    </view>
    <!-- 内容 -->
    <view class="cart_content">
      <view class="cart_title"></view>
      <view class="cart_main">
        <block v-if="cart.length!==0">
          <view class="cart_item" v-for="item in cart" :key="item.goods_id">
            <!-- 左 -->
            <view class="cart_chk_wrap">
              <checkbox-group :id="item.goods_id" @change="handeItemChange">
                <checkbox :checked="item.checked"></checkbox>
              </checkbox-group>
            </view>
            <!-- 中 -->
            <navigator class="cart_img_wrap">
              <image mode="widthFix" :src="item.goods_small_logo" />
            </navigator>
            <!-- 右 -->
            <view class="cart_info_wrap">
              <view class="goods_name">{{item.goods_name}}</view>
              <view class="goods_price_wrap">
                <view class="goods_price">￥{{item.goods_price}}</view>
                <view class="cart_num_tool">
                  <view class="num_deit" @click="handleItemNumEdit(item.goods_id,-1)"> -</view>
                  <view class="goods_num">{{item.num}}</view>
                  <view class="num_deit" @click="handleItemNumEdit(item.goods_id,+1)"> +</view>
                </view>
              </view>
            </view>
          </view>
        </block>
        <block v-else>
          <image
            src="https://gimg2.baidu.com/image_search/src=http%3A%2F%2Fhbimg.b0.upaiyun.com%2Fa4064bdab5f6c800ed664014f3eb7d13a4dd25b3138d0-hYHe07_fw658&refer=http%3A%2F%2Fhbimg.b0.upaiyun.com&app=2002&size=f9999,10000&q=a80&n=0&g=0n&fmt=jpeg?sec=1637134322&t=df6ed6ea0b8b93a44db083af6408e339"
            mode="widthFix" />
          <view><span :style="{'margin-left':120+'rpx','color':'#ccc','font-size':'40rpx'}">购物车空空如也，快去逛逛吧！</span></view>
        </block>
      </view>
    </view>

    <!-- 底部 -->
    <view class="footer_tool">
      <!-- 1 -->
      <view class="all_chk_wrap">
        <checkbox-group @change="handleItemAllCheck">
          <checkbox :checked="allChecked"></checkbox>
        </checkbox-group>
      </view>
      <!-- 2 -->
      <view class="total_price_wrap">
        <view class="total_price">
          合计:<text class="total_price_text">￥{{totalPrice}}</text>
        </view>
        <view>包含运费</view>
      </view>
      <!-- 3 -->
      <view class="order_pay_wrap" @click="handlePay">
        结算({{totalNum}})
      </view>
    </view>
  </view>
</template>

<script>
import {
  getSetting,
  openSetting,
  chooseAddress,
  showToast,
} from "../../utils/asyncWX";
export default {
  data() {
    return {
      address: {},
      cart: [],
      allChecked: false,
      totalPrice: 0,
      totalNum: 0,
    };
  },
  onShow() {
    // 1 获取缓存中的收货地址信息
    const address = uni.getStorageSync("address");
    // 1 获取缓存中的购物车数据
    const cart = uni.getStorageSync("cart") || [];

    this.address = address;
    this.setCart(cart);
  },
  methods: {
    async handlePay() {
      const address = this.address;
      // 购物车数量
      const totalNum = this.totalNum;
      if (!address.userName) {
        const res = await showToast({ title: "您还没有选择收获地址" });
        return;
      }
      if (totalNum === 0) {
        const res = await showToast({ title: "您还没有选购商品" });
        return;
      }
      uni.navigateTo({
        url: "/pages/pay/pay",
      });
    },
    handleItemNumEdit(id, aa) {
      
      let cart = this.cart;
      const goods_id = id;
      const operation = aa;
      cart.map((v, i) => {
        if (v.goods_id == goods_id) {
          var that = this;
          v.num += operation;
          if (v.num < 1 && operation === -1) {
            v.num = 1;
            uni.showModal({
              title: "提示",
              content: "是否要删除该商品",
              success: function (res) {
                if (res.confirm) {
                  cart.splice(i, 1);
                  that.setCart(cart);
                } else if (res.cancel) {
                }
              },
            });
          }
        }
      });
      this.setCart(cart);
    },
    async handleGetUserAddress() {
      try {
        // 1 获取 权限状态
        const res1 = await getSetting();
        const scopeAddress = res1.authSetting["scope.address"];
        // 2 判断 权限状态
        if (scopeAddress === false) {
          await openSetting();
        }
        // 4 调用获取收货地址的 api
        let address = await chooseAddress();
        address.all =
          address.provinceName +
          address.cityName +
          address.countyName +
          address.detailInfo;

        // 5 存入到缓存中
        uni.setStorageSync("address", address);
      } catch (error) {}
    },
    handeItemChange(e) {
      // 1 获取被修改的商品的id

      const goods_id = e.currentTarget.id;
      // 2 获取购物车数组
      let cart = this.cart;
      // 3 找到被修改的商品对象
      console.log(cart, "cart");
      console.log(cart.checked, "cart1");
      // let index = cart.findIndex((v) => {
      //   v.goods_id === parseInt(goods_id);
      // });
      // // 4 选中状态取反
      // console.log(index, "checked");
      // cart[index].checked = !cart[index].checked;

      cart.forEach((v) => {
        if (v.goods_id == goods_id) {
          v.checked = !v.checked;
        }
      });
      this.setCart(cart);
    },
    // 设置购物车状态同时 重新计算 底部工具栏的数据 全选 总价格 购买的数量
    setCart(cart) {
      let allChecked = true;
      // 1 总价格 总数量
      let totalPrice = 0;
      let totalNum = 0;
      cart.forEach((v) => {
        if (v.checked) {
          totalPrice += v.num * v.goods_price;
          totalNum += v.num;
        } else {
          allChecked = false;
        }
      });
      // 判断数组是否为空
      allChecked = cart.length != 0 ? allChecked : false;
      this.cart = cart;
      this.totalPrice = totalPrice;
      this.totalNum = totalNum;
      this.allChecked = allChecked;
      uni.setStorageSync("cart", cart);
    },
    // 商品全选功能
    handleItemAllCheck() {
      // 1 获取data中的数据
      let cart = this.cart;
      let allChecked = this.allChecked;
      // 2 修改值
      allChecked = !allChecked;
      // 3 循环修改cart数组 中的商品选中状态
      cart.forEach((v) => (v.checked = allChecked));
      // 4 把修改后的值 填充回data或者缓存中
      this.setCart(cart);
    },
  },
};
</script>

<style lang="less" scoped>
.revice_address_row {
  .address_btn {
    padding: 20rpx;
    button {
      width: 60%;
    }
  }
  .user_info_row {
    display: flex;

    .user_info {
      flex: 7;
    }
    .user_phone {
      flex: 3;
    }
  }
  .cart_content {
    margin-top: 20rpx;
    .cart_title {
      padding: 20rpx;
      font-size: 36rpx;
      color: #f95314;
      border-top: 1rpx solid currentColor;
      border-bottom: 1rpx solid currentColor;
    }

    .cart_main {
      .cart_item {
        display: flex;
        padding: 10rpx;
        border-bottom: 1rpx solid #ccc;

        .cart_chk_wrap {
          flex: 1;
          display: flex;
          justify-content: center;
          align-items: center;
          checkbox-group {
            checkbox {
            }
          }
        }

        .cart_img_wrap {
          flex: 2;
          display: flex;
          justify-content: center;
          align-items: center;
          image {
            width: 80%;
          }
        }

        .cart_info_wrap {
          flex: 4;
          display: flex;
          flex-direction: column;
          justify-content: space-around;
          .goods_name {
            display: -webkit-box;
            overflow: hidden;
            -webkit-box-orient: vertical;
            -webkit-line-clamp: 2;
            color: #666;
          }

          .goods_price_wrap {
            display: flex;
            justify-content: space-between;
            .goods_price {
              color: #f95314;
              font-size: 34rpx;
            }

            .cart_num_tool {
              display: flex;
              .num_deit {
                width: 55rpx;
                height: 55rpx;
                display: flex;
                justify-content: center;
                align-items: center;
                border: 1rpx solid #ccc;
              }

              .goods_num {
                width: 55rpx;
                height: 55rpx;
                display: flex;
                justify-content: center;
                align-items: center;
              }
            }
          }
        }
      }
    }
  }
}
.footer_tool {
  position: fixed;
  bottom: 0;
  left: 0;
  width: 100%;
  height: 90rpx;
  background-color: #fff;
  display: flex;
  border-top: 1rpx solid #ccc;
  .all_chk_wrap {
    flex: 2;
    display: flex;
    justify-content: center;
    align-items: center;
  }

  .total_price_wrap {
    flex: 5;
    padding-right: 15rpx;
    text-align: right;
    .total_price {
      .total_price_text {
        color: #f95314;
        font-size: 34rpx;
        font-weight: 600;
      }
    }
  }

  .order_pay_wrap {
    flex: 3;
    background-color: #f95314;
    color: #fff;
    font-size: 32rpx;
    font-weight: 600;
    display: flex;
    justify-content: center;
    align-items: center;
  }
}
</style>
